package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.swgk.core.event.MessageEvent;
import com.sgb.kjwl.databinding.ActivityCarriageDetailBinding;
import com.sgb.kjwl.model.entity.transport.DiyFieldEntity;
import com.sgb.kjwl.model.entity.transport.OwnerCarriageDetail;
import com.sgb.kjwl.model.entity.transport.VehicleDetail;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.DriverLocationActivity;
import com.sgb.kjwl.view.ui.adapter.transport.DiyAdapter;
import com.sgb.kjwl.viewmodel.transport.CarriageDetailModel;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.SeeMoreView;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.StringUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * Time:2021/1/11
 * Author:黄淋
 * Description：承运信息详情
 */
@Route(path = AppRouteConstant.WuLui.ROUTER_PATH_VEHICLEDETAILACTIVITY)
public class CarriageDetailActivity extends AppActivity {
    CarriageDetailModel mModel;

    private ActivityCarriageDetailBinding mBinding;
    @Autowired(name = "carrierNo")
    public String carrierNo;
    @Autowired(name = "carriageTypes")
    public int carriageTypes;
    private String mCarrierNo;//承运no
    OwnerCarriageDetail mOwnerCarriageDetail;
    private int mCarriageType = 0;
    private boolean IsMoreInfo = false;
    private VehicleDetail vehicleDetail;

    public static void start(Context context, String carrierNo, int mType) {//mType 0:默认值 1:竞价找车承运详情 2:个人承运需求详情
        Intent intent = new Intent();
        intent.putExtra("carrierNo", carrierNo);
        intent.putExtra("carriageTypes", mType);
        intent.setClass(context, CarriageDetailActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
//        DaggerTransportComponent.builder().appComponent(appComponent)
//                .transportModule(new TransportModule(this))
//                .build()
//                .inject(this);
    }

    @Override
    protected void init() {
        mModel = new ViewModelProvider(this).get(CarriageDetailModel.class);
        mCarrierNo = getIntent().getStringExtra("carrierNo");
        mCarriageType = getIntent().getIntExtra("carriageTypes", 0);
        if (TextUtils.isEmpty(mCarrierNo)) {
            mCarrierNo = carrierNo;
            mCarriageType = carriageTypes;
        }
        if (mCarriageType == 2) {
            mBinding.callPhone.setVisibility(View.GONE);
        }
        mModel.getDetailData(this, mCarrierNo);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mModel.ldCarDetail.observe(this, data -> this.vehicleDetail = data);
        mModel.ldInquiry.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    if (mOwnerCarriageDetail != null)
                        goInquiry();
                } else {
                    MToast.showToast(CarriageDetailActivity.this, "不能对自己发布的承运进行询价！");
                }
            }
        });
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_carriage_detail);
        mBinding.ivBack.setOnClickListener(view -> finish());
        mBinding.callPhone.setOnClickListener(this);
        mBinding.tvCommit.setOnClickListener(this);
        mBinding.tvReport.setOnClickListener(this);
        mBinding.tvInvitation.setOnClickListener(this);
        mBinding.contentView.setVisibility(View.INVISIBLE);
        mBinding.tvInquireByLetter.setOnClickListener(this);
//        mBinding.callPhone.setVisibility(mCarriageType == 2 ? View.GONE : View.VISIBLE);
        mBinding.llLocationLayout.setOnClickListener(this);
        mBinding.llShareLayout.setOnClickListener(this);
        mBinding.tvTakeOrders.setOnClickListener(this);

    }


    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.tv_im:
                if (!ClickUtils.isDoubleClick()) {
                    if (DialogHelper.checkLogin()) {
                        // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                        if (!TextUtils.isEmpty(mOwnerCarriageDetail.getUserVo().getImAccount())) {
                            buildSingleTalking(mOwnerCarriageDetail.getUserVo().getImAccount());
                        }
                    } else {
//                        DialogHelper.showLoginDialog(this);
                        VerificationCodeLoginActivity.start(this);
                    }
                }
                break;
            case R.id.call_phone:
                if (!ClickUtils.isDoubleClick()) {
                    if (DialogHelper.checkLogin()) {
                        DialogHelper.showDialog(CarriageDetailActivity.this,
                                "确认呼叫",
                                mOwnerCarriageDetail.getContrctsNumber(),
                                "确定", new DialogFunction() {
                                    @Override
                                    public void normalRoundDialog() {
                                        ActivityJump.jumpToPhone(CarriageDetailActivity.this, mOwnerCarriageDetail.getContrctsNumber());
                                    }
                                });
                    } else {
                        VerificationCodeLoginActivity.start(this);
                    }
                }
                break;
            case R.id.tv_commit:
                if (!ClickUtils.isDoubleClick()) {
                    if (DialogHelper.checkLogin()) {
                        mModel.refresh(this);
                    } else {
                        VerificationCodeLoginActivity.start(this);
                    }
                }
                break;
            case R.id.tv_inquire_by_letter:
                if (!ClickUtils.isDoubleClick()) {
                    if (DialogHelper.checkLogin()) {
                        if (mOwnerCarriageDetail != null)
                            InquireByLetterActvity.start(this, 3, mOwnerCarriageDetail.getContrcts(), mOwnerCarriageDetail.getUserNo(), mOwnerCarriageDetail.getCarrierNo(),
                                    mOwnerCarriageDetail.getCityName() + "\u3000" + mOwnerCarriageDetail.getDistrictName() + "->" + mOwnerCarriageDetail.getDestCityName() + "\u3000" + mOwnerCarriageDetail.getDestCityName());
                    } else {
                        VerificationCodeLoginActivity.start(this);
                    }
                }
                break;
            case R.id.tv_report:
                if (!ClickUtils.isDoubleClick()) {
                    if (DialogHelper.checkLogin()) {
                        DialogHelper.showDialog(CarriageDetailActivity.this,
                                "确认呼叫",
                                mOwnerCarriageDetail.getContrctsNumber(),
                                "确定", new DialogFunction() {
                                    @Override
                                    public void normalRoundDialog() {
                                        ActivityJump.jumpToPhone(CarriageDetailActivity.this, mOwnerCarriageDetail.getContrctsNumber());
                                    }
                                });
                    } else {
                        VerificationCodeLoginActivity.start(this);
                    }
                }
                //ToastUtil.show(getActivity(), "功能正在开发中");
                break;
            case R.id.tv_invitation:
                LogisticsPermissionHelper.getInstance().checkPermissionToInvite(this, "", 0);
                break;
            case R.id.ll_location_layout://轨迹
                if (vehicleDetail != null) {
                    DriverLocationActivity.start(this, vehicleDetail);
                } else {
                    mModel.loadData(mOwnerCarriageDetail.getCarNo());
                }
                break;
            case R.id.tv_take_orders://下单
                MToast.showToast(this, "功能正在开发中");
                break;
            case R.id.ll_share_layout://分享
                if (mOwnerCarriageDetail == null)
                    return;
                StringBuilder title = new StringBuilder();
                StringBuilder content = new StringBuilder();
                if (!TextUtils.isEmpty(mOwnerCarriageDetail.getCityName())) {
                    title.append(mOwnerCarriageDetail.getCityName());
                }
                if (!TextUtils.isEmpty(mOwnerCarriageDetail.getDistrictName())) {
                    title.append(" ").append(mOwnerCarriageDetail.getDistrictName());
                }
                title.append(" → ");
                if (!TextUtils.isEmpty(mOwnerCarriageDetail.getDestCityName())) {
                    title.append(mOwnerCarriageDetail.getDestCityName());
                }
                if (!TextUtils.isEmpty(mOwnerCarriageDetail.getDestDistrictName())) {
                    title.append(" ").append(mOwnerCarriageDetail.getDestDistrictName());
                }

                content.append("车辆：");
                if (!TextUtils.isEmpty(mOwnerCarriageDetail.getCarTypeName())) {
                    content.append(mOwnerCarriageDetail.getCarTypeName());
                }
                if (!TextUtils.isEmpty(mOwnerCarriageDetail.getCarLenName())) {
                    content.append("/车长").append(mOwnerCarriageDetail.getCarLenName());
                }
                if (mOwnerCarriageDetail.getWeight() != null) {
                    content.append("/");
                    content.append(NumberUtil.trim0(mOwnerCarriageDetail.getWeight()));
                    content.append("吨");
                }
                ShareLogisticsActivity.start(CarriageDetailActivity.this, title.toString(), content.toString(), "", mOwnerCarriageDetail.getShareUrl(), false);
                break;
        }
    }

    public void setDetail(OwnerCarriageDetail ownerCarriageDetail) {
        if (ownerCarriageDetail != null) {
            try {
                this.mOwnerCarriageDetail = ownerCarriageDetail;
                mModel.loadData(ownerCarriageDetail.getCarNo());
                mBinding.llCarriageBottom.setVisibility(1 == mCarriageType ? View.VISIBLE : View.GONE);
                mBinding.contentView.setVisibility(View.VISIBLE);
                if (mCarriageType == 1) {
                    mBinding.updateTime.setVisibility(View.GONE);
                } else {
                    mBinding.llLocationLayout.setVisibility(View.GONE);
                    mBinding.llShareLayout.setVisibility(View.GONE);
                }
                if (ownerCarriageDetail.getDiscuss() == 1) {
                    mBinding.tvDistanceCarriage.setText("商议");
                    mBinding.tvPriceDetailCarriage.setVisibility(View.GONE);
                    mBinding.freightUnit.setVisibility(View.GONE);
                } else {
                    mBinding.tvDistanceCarriage.setText(ownerCarriageDetail.getKilometre() == 0 ? "" : NumberUtil.trim0(ownerCarriageDetail.getKilometre()) + "公里内");
                    mBinding.tvPriceDetailCarriage.setText(ownerCarriageDetail.getFreight());
                    mBinding.freightUnit.setText(ownerCarriageDetail.getFreightUnit());
                }

                if (ownerCarriageDetail.getRadius() != 0) {
                    mBinding.tvSendDetail.setText("市半径" + ownerCarriageDetail.getRadius() / 1000 + "公里内");
                    mBinding.tvDischargeDetail.setText("市半径" + ownerCarriageDetail.getRadius() / 1000 + "公里内");
                    mBinding.tvLoadPlace.setText(ownerCarriageDetail.getProvinceName() + "-" + ownerCarriageDetail.getCityName() + ownerCarriageDetail.getRadius() / 1000 + "公里内");
                } else {
                    mBinding.tvSendDetail.setText("不限");
                    mBinding.tvDischargeDetail.setText("不限");
                    mBinding.tvLoadPlace.setText(ownerCarriageDetail.getProvinceName() + "-" + ownerCarriageDetail.getCityName() + "不限");
                }
                if (ownerCarriageDetail.getHaulDistance() == null) {
                    mBinding.tvYunjuDetail.setText("/");
                } else {
                    mBinding.tvYunjuDetail.setText(ownerCarriageDetail.getHaulDistance() + "公里以上");
                }
                if (ownerCarriageDetail.getFunction() == null || ownerCarriageDetail.getFunction().size() == 0) {
                    mBinding.tvCarFunctionDetail.setText("/");
                } else {
                    StringBuilder builder = new StringBuilder();
                    for (String s : ownerCarriageDetail.getFunction()) {
                        builder.append(s).append("、");
                    }
                    if (builder.length() > 1) {
                        mBinding.tvCarFunctionDetail.setText(builder.subSequence(0, builder.length() - 1));
                    }
                }
                if (ownerCarriageDetail.getCarrierType() != null) {
                    switch (ownerCarriageDetail.getCarrierType()) {
                        case 1:
                            /*     mBinding.include.titleView.setText("承运详情");*/
                            mBinding.tvCarriageTypeDetail.setText("找货承运");
                            break;
                        case 2:
                            /*  mBinding.include.titleView.setText("竞价承运详情");*/
                            mBinding.tvCarriageTypeDetail.setText("竞价找货");
                            break;
                        case 3:
                            /*   mBinding.include.titleView.setText("特价承运详情");*/
                            mBinding.tvCarriageTypeDetail.setText("返程货运");
                            break;
                    }
                } /*else {
                mBinding.include.titleView.setText("承运详情");
            }*/
                mBinding.setDetailEntity(ownerCarriageDetail);
                if (ownerCarriageDetail.getMessageStatus() == 1) {
                    mBinding.ivState.setVisibility(View.INVISIBLE);
                } else {
                    mBinding.ivState.setVisibility(View.VISIBLE);
                    mBinding.tvCommit.setEnabled(false);
                    mBinding.tvCommit.setAlpha(0.6f);
                    mBinding.tvTakeOrders.setEnabled(false);
                    mBinding.tvTakeOrders.setAlpha(0.6f);
                }
                if (ownerCarriageDetail.getUserVo() == null || ownerCarriageDetail.getUserVo().getImToken() == null || ownerCarriageDetail.getUserVo().getImToken().isEmpty()) {
                    mBinding.tvIm.setAlpha(0.6f);
                } else {
                    mBinding.tvIm.setOnClickListener(this);
                }

                if (ownerCarriageDetail.getUpdateTime() != null) {
                    mBinding.updateTime.setText("更新时间：" + (DateUtils.stampToDay(String.valueOf(ownerCarriageDetail.getUpdateTime()))));
                }
                if (ownerCarriageDetail.getShipmentStartTime() != null && ownerCarriageDetail.getShipmentEndTime() != null) {
                    if (DateUtils.stampToDay5(String.valueOf(ownerCarriageDetail.getShipmentStartTime())).equals(DateUtils.stampToDay5(String.valueOf(ownerCarriageDetail.getShipmentEndTime())))) {
                        mBinding.uploadTime.setText(DateUtils.stampToDay5(String.valueOf(ownerCarriageDetail.getShipmentStartTime())));
                    } else {
                        mBinding.uploadTime.setText(DateUtils.stampToDay5(String.valueOf(ownerCarriageDetail.getShipmentStartTime())) + '-' +
                                DateUtils.stampToDay5(String.valueOf(ownerCarriageDetail.getShipmentEndTime())));
                    }
                }

                if (ownerCarriageDetail.getContrctsNumber() != null) {
                    mBinding.connectPersonPhone.setText(mCarriageType == 1 ? StringUtil.gonePhone(ownerCarriageDetail.getContrctsNumber()) : ownerCarriageDetail.getContrctsNumber());
                }

                //额定载重
                if (ownerCarriageDetail.getWeight() != null) {
                    mBinding.weightLayout.setVisibility(View.VISIBLE);
                    mBinding.weight.setText(NumberUtil.trim0(ownerCarriageDetail.getWeight()) + "吨");
                } else {
                    mBinding.weightLayout.setVisibility(View.GONE);
                }

                //栏高/是否自卸
                StringBuffer bufferHD = new StringBuffer();
                if (!TextUtils.isEmpty(ownerCarriageDetail.getHeightHurdle())) {
                    bufferHD.append(NumberUtil.trim0(ownerCarriageDetail.getHeightHurdle()) + "米");
                }
                if (ownerCarriageDetail.getIsDump() != null) {
                    if (bufferHD.toString().length() > 0)
                        bufferHD.append("/");
                    bufferHD.append(ownerCarriageDetail.getIsDump() == 1 ? "自卸" : "非自卸");
                }
                if (bufferHD.toString().length() > 0) {
                    mBinding.tvHeightDump.setText(bufferHD.toString());
                } else {
                    mBinding.tvHeightDump.setText("/");
                }

                //付款方式
                if (ownerCarriageDetail.getPayType().equals("/")) {
                    mBinding.payType.setText(ownerCarriageDetail.getPayType());
                } else {
                    IsMoreInfo = true;
                    mBinding.payType.setText(ownerCarriageDetail.getPayType());
                }
                //发票要求
                if (TextUtils.isEmpty(ownerCarriageDetail.getInvoiceName())) {
                    mBinding.tvFapiaoYaoqiu.setText("/");
                } else {
                    IsMoreInfo = true;
                    mBinding.tvFapiaoYaoqiu.setText(ownerCarriageDetail.getInvoiceName());
                }
                //是否可议价
//            if (ownerCarriageDetail.getBargain() != null) {
//                IsMoreInfo = true;
//                mBinding.tvRateBargainingDetail.setText(ownerCarriageDetail.getBargain() == 1 ? "可议价" : "不可议价");
//                mBinding.tvRateBargainingDetailLayout.setVisibility(View.VISIBLE);
//            } else {
//                mBinding.tvRateBargainingDetailLayout.setVisibility(View.GONE);
//            }
                //备注
                SeeMoreView carriage_note = mBinding.carriageNote;
                if (!TextUtils.isEmpty(ownerCarriageDetail.getNote())) {
                    IsMoreInfo = true;
                    mBinding.carriageNote.setText(ownerCarriageDetail.getNote().trim());
                } else {
                    mBinding.carriageNote.setText("/");
                }

                //自定义字段
                setDiyField(mBinding.rvItemCustom, ownerCarriageDetail.getDiyField());

                //1：企业 2：团队 3:个人
                RequestOptions options;
                if (ownerCarriageDetail.getTerminal() == 1) {
                    options = new RequestOptions()
                            .placeholder(R.mipmap.icon_company_default)
                            .fallback(R.mipmap.icon_company_default)
                            .error(R.mipmap.icon_company_default)
                            .centerCrop();
                } else if (ownerCarriageDetail.getTerminal() == 2) {
                    options = new RequestOptions()
                            .placeholder(R.mipmap.icon_team_default_1)
                            .fallback(R.mipmap.icon_team_default_1)
                            .error(R.mipmap.icon_team_default_1)
                            .centerCrop();
                } else {
                    options = new RequestOptions()
                            .placeholder(R.drawable.geren_person_touxiang)
                            .fallback(R.drawable.geren_person_touxiang)
                            .error(R.drawable.geren_person_touxiang)
                            .centerCrop();
                }

                if (ownerCarriageDetail.getUserVo() != null && !TextUtils.isEmpty(ownerCarriageDetail.getUserVo().getHeadImg())) {
                    Glide.with(this).load(ownerCarriageDetail.getImg()).apply(options).into(mBinding.ivHeader);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 自定义字段列表显示
     *
     * @param recyclerView
     * @param diyField
     */
    private void setDiyField(RecyclerView recyclerView, List<DiyFieldEntity> diyField) {
        if (diyField == null || diyField.size() == 0) {
            recyclerView.setVisibility(View.GONE);
            return;
        }
        IsMoreInfo = true;
        recyclerView.setVisibility(View.VISIBLE);
        //自定义字段，展开收起控件调整
        DiyAdapter adapter = new DiyAdapter(diyField);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    private void goInquiry() {
        //TODO 去询价界面
        InquiryActivity.startCarriageInquiry(CarriageDetailActivity.this, mOwnerCarriageDetail.getCarrierNo(), mOwnerCarriageDetail.getContrctsNumber());
    }

    public void setUserInfo() {
        if (UserOperating.getInstance().isNotOpenFundAccount(this, PermissionCheckUtil.KEY_WODEXUNJIA)) {
            return;
        }
        mModel.getInquiryPermissions(mOwnerCarriageDetail.getCarrierNo());
    }

    //开通个人资金账户后判断
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCode(MessageEvent event) {
        switch (event.code) {
            case EventConstant.EVENT_REFRESH:
                UserOperating.getInstance().refresh();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
